<template>
  <el-card class="upload-form" shadow="hover">
    <template #header>
      <div class="form-title">上传新题目</div>
    </template>

    <el-form :model="form" label-width="100px" @submit.prevent="handleSubmit">
      <el-form-item label="题干">
        <el-input v-model="form.content" rows="3" type="textarea" />
      </el-form-item>

      <el-form-item label="题型">
        <el-select v-model="form.type" placeholder="请选择题型">
          <el-option :value="'SINGLE_CHOICE'" label="单选题" />
          <el-option :value="'MULTIPLE_CHOICE'" label="多选题" />
          <el-option :value="'FILL_IN_BLANK'" label="填空题" />
          <el-option :value="'SUBJECTIVE'" label="主观题" />
        </el-select>
      </el-form-item>

      <el-form-item label="选项">
        <el-input
          v-model="form.options"
          placeholder='请输入选项 JSON，如：["A. 选项1", "B. 选项2"]'
          rows="4"
          type="textarea"
        />
      </el-form-item>

      <el-form-item label="答案">
        <el-input
          v-model="form.answer"
          placeholder='请输入答案 JSON，如："A" 或 ["A", "B"]'
          rows="2"
          type="textarea"
        />
      </el-form-item>

      <el-form-item label="解析">
        <el-input v-model="form.analysis" rows="3" type="textarea" />
      </el-form-item>

      <el-form-item label="难度">
        <el-slider v-model="form.difficulty" :max="1" :min="0" :step="0.01" show-input />
      </el-form-item>

      <el-form-item label="所属学科">
        <el-select v-model="selectedSubject" placeholder="请选择学科" @change="handleSubjectChange">
          <el-option
            v-for="subject in AllSubjects"
            :key="subject"
            :label="subject"
            :value="subject"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="知识点搜索">
        <el-input
          v-model="searchKeyword"
          clearable
          placeholder="搜索知识点"
          @input="onSearchInput"
        />
      </el-form-item>

      <el-form-item label="知识点">
        <el-select
          v-model="form.knowledgePointNames"
          filterable
          multiple
          placeholder="请选择知识点"
          style="width: 100%"
        >
          <el-option
            v-for="kp in knowledgePoints"
            :key="kp.kpId"
            :label="kp.name"
            :value="kp.name"
          />
        </el-select>

        <el-pagination
          :current-page="page"
          :page-size="pageSize"
          :total="totalKnowledgePoints"
          background
          layout="prev, pager, next"
          small
          style="margin-top: 10px"
          @current-change="handlePageChange"
        />
      </el-form-item>

      <el-form-item label=" " style="text-align: right">
        <el-button :loading="loadingAI" type="success" @click="generateQuestionFromAI">
          使用 AI 生成题目
        </el-button>
      </el-form-item>

      <el-form-item label=" ">
        <el-button @click="previewMarkdown">预览 Markdown</el-button>
      </el-form-item>

      <el-form-item v-if="renderedMarkdown">
        <div class="markdown-box" v-html="renderedMarkdown"></div>
      </el-form-item>

      <el-form-item>
        <el-button :disabled="!isFormValid" type="primary" @click="handleSubmit">提交</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script lang="ts" setup>
import { computed, ref } from 'vue'
import { apiClient, handleErrorAndRedirect } from '@/api'
import { ElMessage } from 'element-plus'
import { AllSubjects, renderMarkdown } from '@/api/utils.ts'

interface knowledgePoint {
  kpId: number
  name: string
  subject: string
  description: string
  status: string
}

const form = ref({
  content: '',
  type: '',
  options: '',
  answer: '',
  analysis: '',
  difficulty: 0.5,
  knowledgePointNames: [],
})

const loadingAI = ref(false)

const generateQuestionFromAI = async () => {
  if (
    !selectedSubject.value ||
    !form.value.type ||
    !form.value.difficulty ||
    form.value.knowledgePointNames.length === 0
  ) {
    ElMessage.warning('请选择学科,知识点和题型')
    return
  }
  if (form.value.type !== 'SINGLE_CHOICE') {
    ElMessage.warning('AI 目前仅支持生成单选题')
    return
  }

  const knowledgePointName = form.value.knowledgePointNames[0]
  loadingAI.value = true
  try {
    const res = await apiClient.post('admin/questions/generate', {
      knowledge_point_name: knowledgePointName,
      subject: selectedSubject.value,
      question_type: form.value.type,
      difficulty: form.value.difficulty,
    })

    const aiData = res.data

    form.value.content = aiData.content || ''
    form.value.options = JSON.stringify(aiData.options || {}, null, 2)
    form.value.answer = JSON.stringify(aiData.answer || '')
    form.value.analysis = aiData.analysis || ''

    ElMessage.success('AI 生成题目成功')
  } catch (err) {
    handleErrorAndRedirect(err, 'AI 生成失败')
  } finally {
    loadingAI.value = false
  }
}

const selectedSubject = ref<string | null>(null)

const knowledgePoints = ref<knowledgePoint[]>([])
const totalKnowledgePoints = ref(0)
const page = ref(1)
const pageSize = 10
const searchKeyword = ref('')

const isFormValid = computed(() => {
  const f = form.value
  return (
    f.content.trim() !== '' &&
    f.type.trim() !== '' &&
    f.options.trim() !== '' &&
    f.answer.trim() !== '' &&
    f.analysis.trim() !== '' &&
    f.difficulty >= 0 &&
    f.difficulty <= 1 &&
    f.knowledgePointNames.length > 0 &&
    selectedSubject.value !== null &&
    selectedSubject.value.trim() !== ''
  )
})

const fetchKnowledgePoints = async () => {
  if (!selectedSubject.value) return
  try {
    const res = await apiClient.get(`/admin/knowledge-points/APPROVED/${page.value}`, {
      params: {
        subject: selectedSubject.value,
        keyword: searchKeyword.value,
      },
    })
    knowledgePoints.value = res.data.data
    totalKnowledgePoints.value = res.data.total
  } catch (error) {
    handleErrorAndRedirect(error, '加载知识点失败')
  }
}

const renderedMarkdown = ref('')

const previewMarkdown = () => {
  try {
    const optionsRaw = form.value.options
    let optionsSection = ''
    if (optionsRaw) {
      const parsed = JSON.parse(optionsRaw)
      if (Array.isArray(parsed)) {
        optionsSection = parsed.map((opt) => `- ${opt}`).join('\n')
      } else if (typeof parsed === 'object') {
        optionsSection = Object.entries(parsed)
          .map(([key, value]) => `- **${key}.** ${value}`)
          .join('\n')
      }
    }

    const markdown = `
### 题干

${form.value.content || ''}

### 选项

${optionsSection}

### 答案

${form.value.answer || ''}

### 解析

${form.value.analysis || ''}
    `.trim()

    renderedMarkdown.value = renderMarkdown(markdown)
  } catch (error) {
    ElMessage.error('选项格式错误，无法预览')
    renderedMarkdown.value = ''
  }
}

const onSearchInput = () => {
  page.value = 1
  fetchKnowledgePoints()
}

const handlePageChange = (newPage: number) => {
  page.value = newPage
  fetchKnowledgePoints()
}

const handleSubjectChange = () => {
  page.value = 1
  fetchKnowledgePoints()
}

const resetForm = () => {
  form.value = {
    content: '',
    type: '',
    options: '',
    answer: '',
    analysis: '',
    difficulty: 0.5,
    knowledgePointNames: [],
  }
  selectedSubject.value = null
  searchKeyword.value = ''
  page.value = 1
  knowledgePoints.value = []
  totalKnowledgePoints.value = 0
}

const handleSubmit = async () => {
  if (!isFormValid.value) {
    ElMessage.error('请完整填写所有必填字段和选择知识点后再提交')
    return
  }
  try {
    await apiClient.post('/admin/questions', form.value)
    ElMessage.success('题目上传成功')
    resetForm()
  } catch (error) {
    handleErrorAndRedirect(error, '上传失败')
  }
}
</script>

<style scoped>
.upload-form {
  max-width: 700px;
  margin: 40px auto;
}

.form-title {
  font-size: 20px;
  font-weight: bold;
  text-align: center;
}

.markdown-box {
  border: 1px solid #ddd;
  padding: 16px;
  border-radius: 6px;
  background-color: #f8f8f8;
  max-height: 500px;
  overflow-y: auto;
  line-height: 1.6;
}

.markdown-box h3 {
  margin-top: 1em;
  color: #333;
}
</style>
